from sqlalchemy.orm import Session
from sqlalchemy import text
import json
from typing import List
from app.entity import SysRole, SysRoleMenu
from app.schema import RoleData
from utils.request import PageInfo

class RoleModel:
    """
    菜单管理模块数据库操作层
    """
    @classmethod
    def get_select_options(cls, db: Session):
        opts = db.query(SysRole).filter(SysRole.status==0).all()
        
        return opts

    @classmethod
    def insert(cls, db: Session, data: RoleData):
        dic = data.dict()
        
        menuIds = dic['menuKeys']
        del dic['menuKeys']

        db_post = SysRole(**dic)
        db.add(db_post)
        db.flush()
        
        res = db.execute(text("SELECT LAST_INSERT_ID() as last_id"))
        newID = res.first()
        
        if newID:
            for v in menuIds:
                newData = SysRoleMenu(**{'role_id':newID[0], 'menu_id':v})
                db.add(newData)
                db.flush()
        
        db.commit()
        
        return True
    

    @classmethod
    def edit(cls, db: Session, post: dict):
        
        menuIds = post['menuKeys']
        del post['menuKeys']

        db.query(SysRole).filter(SysRole.role_id == post.get('role_id')).update(post)
        db.query(SysRoleMenu).filter(SysRoleMenu.role_id==post.get('role_id')).delete()
        
        for v in menuIds:
            newData = SysRoleMenu(**{'role_id':post.get('role_id'), 'menu_id':v})
            db.add(newData)
            db.flush()
        
        db.commit()

    @classmethod
    def delete(cls, db: Session, ids: List[int]):
        db.query(SysRole).filter(SysRole.role_id.in_(ids)).delete()
        db.query(SysRoleMenu).filter(SysRoleMenu.role_id.in_(ids)).delete()
        db.commit()

    @classmethod
    def get_by_id(cls, db: Session, id: int):
        return db.query(SysRole).filter(SysRole.role_id==id).first()
        

    @classmethod
    def get_page(cls, db: Session, where:dict, page: PageInfo ):
        total = db.query(SysRole).filter_by(**where).count()
        rows  = db.query(SysRole).filter_by(**where).offset((page.page-1)*page.limit).limit(page.limit).all()
        
        return total, rows
        
        
    @classmethod
    def get_role_menus(cls, db: Session, id:int):
        menuIds = db.query(SysRoleMenu).filter(SysRoleMenu.role_id==id).all()
        return menuIds
    
    @classmethod
    def get_role_list(cls, db: Session):
        rows = db.query(SysRole.role_id,SysRole.role_name).filter(SysRole.status=='0').all()
        
        return [ {"id":v[0],"name":v[1],"children":[]} for v in rows]